#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask_restful import Resource, reqparse
from flask import jsonify,g ,make_response

from service.articleService import ArticleService
from controller.articleController import ArticleController
from utils import commons
from utils.response_code import RET


class ArticleOtherResource(Resource):

    @classmethod
    def sensitive_update(cls, article_id):
        if not article_id:
            return jsonify(code=RET.NODATA, message='primary key missed', error='primary key missed')

        parser = reqparse.RequestParser()
        parser.add_argument('status', location='form', required=False, help='status参数类型不正确或缺失')
        parser.add_argument('is_delete', location='form', required=False, help='is_delete参数类型不正确或缺失')
        
        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)
        kwargs['article_id'] = article_id

        res = ArticleController.update(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])

    # 用户上传文章
    @classmethod
    def add_article(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('article_title', type=str, location='form', required=True,
                            help='article_title参数类型不正确或缺失')
        parser.add_argument('article_content', type=str, location='form', required=True,
                            help='article_content参数类型不正确或缺失')

        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)
        kwargs['user_id'] = g.user.get('user_id')


        if not all([kwargs['article_title'], kwargs['article_content'], kwargs['user_id']]):
            return jsonify({'code': RET.PARAMERR, 'message': '参数错误', 'data': None})

        result = ArticleService.add_article(kwargs['article_title'], kwargs['article_content'], kwargs['user_id'])
        return jsonify(result)

    # 获取已审核文章
    @classmethod
    def get_approved_articles(cls):
        articles = ArticleService.get_approved_articles()
        return jsonify(articles)

    # 获取未审核文章
    @classmethod
    def get_disapproved_articles(cls):
        articles = ArticleService.get_disapproved_articles()
        return jsonify(articles)

    # 管理员审核文章
    @classmethod
    def approve_article(cls, article_id):
        administrator_id = g.user.get('user_id')
        if not all([article_id, administrator_id]):
            return jsonify({'code': RET.PARAMERR, 'message': '参数错误', 'data': None})
        return ArticleService.approve_article(article_id, administrator_id)

    @classmethod
    def delete_article(cls, article_id):
        administrator_id = g.user.get('user_id')
        if not all([article_id, administrator_id]):
            return jsonify({'code': RET.PARAMERR, 'message': '参数错误', 'data': None})
        return ArticleService.delete_article(article_id, administrator_id)